package com.ncmmall.api.apis.mall;

import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.merchant.MerchantApplication;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * @Description: 邀请商家模块
 * @Date: 2019-07-22 14:15
 */
@RestController
@RequestMapping(value = "/merchant")
@Component
public class MerchantApi {

    private final static Logger logger = LoggerFactory.getLogger(MerchantApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantApplication merchantApplication;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 邀请商家审核列表
     *
     * @param request
     * @param pageNo
     * @param pageSize
     * @param status
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public Result list(HttpServletRequest request, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "0") int status) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
            Map<String, Object> params = Maps.newHashMap();
            params.put("id", member.getId());

            String hql = builderHql("select u.id, u.createTime, u.shopName,u.realName,u.mobile,u.merchantCheckStatus from security_web_user u where u.fatherMember_id = :id and u.role_id = 4 ", params, status);
            QueryPage<Map<String, Object>> page = queryChannelService.selectPageMap(hql, pageRequest.setParams(params));

            return result.ok().inject(ImmutableMap.of("page", page));

        } catch (Exception e) {
            logger.error("[邀请商家列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }

    /**
     * 商家申请入驻
     *
     * @param merchant
     * @return
     */
    @PostMapping("/apply")
    public Result apply(HttpServletRequest request, @RequestBody WebUser merchant) {
        Result result = new Result();
        try {

            merchant.setUsername(merchant.getMobile());
            merchant.setPassword("123456");
            merchant.setRelevanceMember(Securitys.user(request));

            merchantApplication.createMerchant(merchant);

            return result.ok();
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("[邀请商家入驻异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }

    /**
     * 重新申请
     *
     * @param merchant
     * @return
     */
    @PostMapping("/reapply")
    public Result reapply(@RequestBody WebUser merchant) {
        Result result = new Result();
        try {

            merchantApplication.modifyMerchant(merchant);
            merchant.setMerchantCheckStatus(1);
            merchantApplication.checkMerchant(merchant);

            return result.ok();
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("[邀请商家入驻异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }


    /**
     * 通过openID获取当前的商家入驻申请状态
     */
    @GetMapping("/applyStatus")
    public Result applyStatus(HttpServletRequest request) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);
            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.relevanceMember.id.eq(member.getId()).and(QWebUser.webUser.role.name.eq("MERCHANT")), WebUser.class);
            Map<String, Object> data = new HashMap<>();

            if (merchant != null) {
                Securitys.cleanUser(merchant);
            }
            data.put("merchant", merchant);

//            data.put("merchant", null != merchant ? Securitys.cleanUser(merchant) : merchant);
            return result.ok().inject(data);

        } catch (Exception e) {
            logger.error("[邀请商家入驻异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }


    /**
     * 获取经营类目
     */
    @GetMapping("/channels")
    public Result channels() {
        Result result = new Result();
        try {

            List<Map<String, Object>> channels = queryChannelService.selectAllMap("select * from mall_goods_channel where status = 1 and level = 1 and deleteStatus = 0 ", new HashMap<>());

            return result.ok().inject(ImmutableMap.of("channels", channels));

        } catch (Exception e) {
            logger.error("[邀请商家入驻异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }


    private String builderHql(String hql, Map<String, Object> params, int status) {

        if (status > 0) {
            hql += " and u.merchantCheckStatus = :status ";
            params.put("status", status);
        }

        return hql;
    }

}
